const Database=require("better-sqlite3");
const path=require("path");
const db=new Database(path.join(__dirname,"./mydata.sqlite"),{
    fileMustExist:true,
    verbose:console.log
});

const registerFun=function(user={}){
    let sql=`insert into t_user (username,password) values (?,?)`;
    let stmt=db.prepare(sql);
    let row=stmt.run(user.username,user.password);
    return row;
};

const loginFun=function(user={}){
    let sql=`select id,username,password from t_user where username=? and password=?`;
    let stmt=db.prepare(sql);
    let u=stmt.get(user.username,user.password);
    return u;
};

const findAllClass=function(){
    let sql=`select id,name from t_class`;
    let stmt=db.prepare(sql);
    let rows=stmt.all();
    return rows;
};

const findClassById=function(id=""){
    let sql=`select id,name from t_class where id=?`;
    let stmt=db.prepare(sql);
    let rows=stmt.get(id);
    return rows;
};

const updateClassById=function(classData={}){
    let sql=`update t_class set name=? where id=?`;
    let stmt=db.prepare(sql);
    let rows=stmt.run(classData.name,classData.id);
    return rows;
};

const deleteClassById=function(id=""){
    let sql="delete from t_class where id=?";
    let stmt=db.prepare(sql);
    let rows=stmt.run(id);
    return rows;
};

module.exports={
    "registerFun":registerFun,
    "loginFun":loginFun,
    "findAllClass":findAllClass,
    "findClassById":findClassById,
    "updateClassById":updateClassById,
    "deleteClassById":deleteClassById
};